from django.core.urlresolvers import resolve
from kingadmin.permission_list import permission_dict
from django.shortcuts import redirect,render,HttpResponse
from django.utils.safestring import mark_safe

def check_permission(*args,**kwargs):
    request=args[0]
    request_url=resolve(request.path).url_name
    match_key=None
    args_check=None
    kwarg_check=None
    if request.user.is_authenticated() is False:
        return redirect('/login/')

    for permission_key,val in permission_dict.items():
        print('执行args 权限检查-------------')
        per_url=val[0]
        per_method=val[1]
        per_args=val[2]
        per_kwargs=val[3]
        per_hook_func=val[4] if len(permission_dict[permission_key]) > 4 else None

        if request_url == per_url:
            if request.method == per_method:
                args_check=False
                for arg in per_args:
                    request_func=getattr(request,per_method)
                    if request_func.get(arg,None):
                        args_check=True
                        print('存在arg参数')
                    else:
                        print('不存在指定arg参数')
                        args_check=False
                        break
                else:
                    print('未作权限限制，，默认通过')
                    args_check=True
                kwarg_check=False

                for arg_name,arg_val in per_kwargs.items():
                    print('执行 kwargs 权限检查-------------')
                    request_func=getattr(request,per_method)
                    if request_func.get(arg_name) == str(arg_val):
                        kwarg_check=True
                    else:
                        kwarg_check=False
                        break
                else:
                    kwarg_check=True
                    print('未作 kwargs 限制，默认通过')

                per_func=False
                print('执行用户自定义钩子函数')
                if per_hook_func:
                    per_func=per_hook_func(request)
                else:
                    per_func=True

                per_res=[args_check,kwarg_check,per_func]
                if all(per_res):
                    match_key=permission_key
                    print('权限匹配结果:',per_res)
                    break

    if all(per_res):
        appname,*per_name=match_key.split('_')
        per_obj='%s.%s'%(appname,match_key)

        if request.user.has_perm(per_obj):
            print('所有权限检查通过')
            return True
        else:
            print('权限检查未通过')
            return False
    else:
        print('未匹配到权限')
        return False




def check_per(func):
    def inner(*args,**kwargs):
        if not check_permission(*args,**kwargs):
            return HttpResponse(mark_safe('<h1>403 你没有相应的权限</h1>'))
        else:

            return func(*args,**kwargs)
    return inner